using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Net;
using System.IO;
using System.ComponentModel;
using System.Web;

namespace SoftwareMonkeys.Scriptech.Scripts
{
	public class ScriptPanel : Panel
	{
		/// <summary>
		/// 
		/// </summary>
		[Bindable(true)]
		public string ScriptName
		{
			get {
				if (ViewState["ScriptName"] != null)
					return (string)ViewState["ScriptName"];
				else
					return Page.Request.QueryString["Script"];
			}
			set { ViewState["ScriptName"] = value; }
		}
		
		public string QueryStrings
		{
			get {
				if (ViewState["QueryStrings"] != null)
					return (string)ViewState["QueryStrings"];
				else
					return String.Empty;
			}
			set { ViewState["QueryStrings"] = value; }
		}
		
		public string TmpFolder
		{
			get {
				if (ViewState["TmpFolder"] != null)
					return (string)ViewState["TmpFolder"];
				else
					return String.Empty;
			}
			set { ViewState["TmpFolder"] = value; }
		}
		
		public ScriptPanel ()
		{
		}
		
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			//string scriptPath = ScriptsUtil.GetScriptPath(ScriptName);
			
			Controls.Add(new LiteralControl("<div>Script: " + ScriptName + "</div>"));
			
			string queryString = QueryStrings;
			
			//Control scriptControl = ScriptLauncher.Launch(ScriptName, Page);
			if (queryString != String.Empty)
				queryString = "?" + queryString;
			
			queryString = queryString.IndexOf("?") == -1 ? "?" : "&";
			queryString = queryString + "ShowTemplate=false";
			
			string url = Scripts.MapUrl(ScriptName, queryString);
			
			WebRequest request = HttpWebRequest.Create(url);
			
			string content = String.Empty;
			
			try
			{
				content = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
			}
			catch
			{
				throw new Exception("\"404 - not found\" error; calling '" + url + "'.");
			}
			
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(content);
			
			string data = doc.DocumentNode.SelectSingleNode("//body").InnerHtml;
			
			LiteralControl control = new LiteralControl(data);
			
			Controls.Add(control);
			
			//control.RenderControl(((BaseScript)Container).OutputWriter);
			//Controls.Add(scriptControl);
			
		}
		
	}
}

